import React, {
  useCallback,
  useEffect,
  useState,
  useRef,
  useMemo,
} from "react";
import {
  Button,
  Card,
  Checkbox,
  Col,
  Form,
  Input,
  message,
  Modal,
  Row,
  Select,
  Spin,
  Switch,
  Alert,
  Typography,
  Radio,
  Tooltip,
} from "antd";
import { connect } from "dva";

import { BottomAction } from "@/components";
import IconFont from "@/components/IconFont";
import { defaultFormatResult } from "@/hooks";
import { withRoutePage } from "@/utils/enhanceUtils";
import { isSuccess } from "@/utils/request";
import pageTabUtil from "@/utils/pageTabUtil";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import PageRouter from "@/components/PageRouter/PageRouter";

import {
  onAddSalaryItem,
  onEditSalaryItemFirst,
  onEditSalaryItemSecond,
  queryConditionList,
  queryDictList,
  queryFlowTypeList,
  queryParentSalaryItemList,
  querySalaryItemInfo,
} from "@/services/salaryManage/salaryCalculate";
import {
  COMMON_NAME,
  pageTabProps,
  makeArray,
  arrayToString,
  getCurrentOrgCountryCode,
} from "@/pages/SalaryManage/utils";

import LimitInput from "@/components/LimitInput";
import salaryStyle from "@/pages/SalaryManage/salaryManage.less";
// import FormulaEditor from '@/pages/SalaryManage/SalaryCalculate/TemplateSetting/components/FormulaEditor';
import tabMessageUtil from "@/pages/SalaryManage/utils/tabMessageUtil";
import { OrganizationNameConnect } from "@/pages/SalaryManage/components/OrganizationName";
import { SINGAPORE_CODE } from "@/pages/SalaryManage/constant/countryRegion";
import SelectedStaffEdit from "./selectedStaffEdit";
import useSelectCondition from "./hooks/useSelectCondition";

import { convert2EditorFormula, convert2ServerFormula } from "./formulaConvert";
// import Editor from './editor';
import Special from "./special";
import styles from "./index.less";

const { Text } = Typography;
const { Option } = Select;
const RadioGroup = Radio.Group;
const DICT_NAME_LIST = [
  "salaryObjectOptions",
  "salaryNotOptions",
  "booleanOptions",
  "taxTypeOptions",
  "salaryItemTypeOptions",
  "flowTypeOptions",
  "conditionOptions",
  "salaryTypeOptions",
];
// 部分员工key常量
const PART_STAFF_KEY = 8;

// 需要数组转化成字符串字段
const arrToStringFields = ["salaryNot"];

// 日期模式
const DAY_TYPES = [
  {
    label: "工作日",
    value: 1,
  },
  {
    label: "自然日",
    value: 2,
  },
];
// 要刷新界面
const REFRESH_PAGE = [
  // 薪资要素编辑界面
  "/finance/salary/salarytemplateedit",
  // 薪资项清单个界面
  "/finance/salary/calculate/templatesetting/parttemplate",
  // 薪资模板界面
  "/finance/salary/calculate/templatesetting/salarytemplate",
];

const TemplateSalaryModal = ({ form, location, organizationCode }) => {
  const {
    itemType = "add",
    entry = "single",
    disabled: disabledStr,
    id,
  } = location.query;
  const disabled = { true: true, false: false }[disabledStr] ?? false;
  const {
    getFieldDecorator,
    validateFields,
    getFieldValue,
    setFieldsValue,
  } = form;
  const [modalDictList, setModalDictList] = useState({});
  const [flowList, setFlowList] = useState([]);
  const [parentSalaryItemList, setParentSalaryItemList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [formItemType, setFormItemType] = useState("add");
  const [editData, setEditData] = useState({});
  const [conditionList, setConditionList] = useState([]);
  const [salaryObject, setSalaryobject] = useState(editData.salaryObject);
  const selectList = useSelectCondition(conditionList);
  const [specialAmount, setSpecialAmount] = useState(0);
  const [formula, setFormula] = useState("");
  const selectedStaffEditRef = useRef(null);
  // 是否是选择部分员工
  const isPartStaff = useMemo(() => salaryObject === PART_STAFF_KEY, [
    salaryObject,
  ]);

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 7 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 17 },
    },
  };
  const getModalDictList = async () => {
    try {
      const confTypes = DICT_NAME_LIST.join(",");
      const { code, data = {} } = await queryDictList(confTypes);
      if (code === 10000) {
        console.log("modal数据字典列表", data);
        setModalDictList(data);
      }
    } catch (e) {
      console.log("获取modal中的字段列表失败", e);
    }
  };
  const getFlowList = async (type) => {
    try {
      const queryItemType = type || "add";
      const postData = queryItemType === "add" ? 2 : 3;
      const flowDatas = await queryFlowTypeList({
        organizationCode,
        itemType: postData,
      }).then(defaultFormatResult.formatResult);
      setFlowList(flowDatas || []);
    } catch (e) {
      console.log("获取审批流取值失败");
    }
  };
  const getDictList = (key, condition) => {
    if (typeof condition !== "undefined") {
      return modalDictList[key]
        ? modalDictList[key].filter(
            (item) => item.filter && item.filter.indexOf(condition) !== -1
          )
        : [];
    }
    return modalDictList[key] || [];
  };
  const getParentSalaryItemList = async (type) => {
    if (organizationCode) {
      try {
        const queryItemType = type || "add";
        const postData = queryItemType === "add" ? 2 : 3;

        const { code, data = [] } = await queryParentSalaryItemList(
          organizationCode,
          postData
        );
        if (code === 10000) {
          setParentSalaryItemList(data);
        }
      } catch (e) {
        console.log(e);
      }
    }
  };
  const goBack = () => {
    pageTabUtil.closeTab(pageTabUtil.getCurrentKey());
  };

  useEffect(() => {
    if (specialAmount) {
      setFormula("");
      form.setFieldsValue({
        serverFormula: undefined,
        hasErrorInServerFormula: false,
        formulaFlow: undefined,
      });
    }
  }, [specialAmount]);
  const handleSalaryObject = (value) => {
    setSalaryobject(value);
    if (value !== PART_STAFF_KEY) {
      setSpecialAmount(undefined);
    }
  };
  const onAdd = async (values) => {
    try {
      setLoading(true);
      const params = {
        organizationCode,
        ...values,
        formulaFunc: values.serverFormula,
      };
      // 编辑
      if (id) {
        const handleResponse = (response, confirmFn = () => {}) => {
          const { code, msg, data = {} } = response;
          if (!isSuccess(code)) {
            message.error(msg);
            return;
          }

          if (data.enableLevel === 1) {
            message.success("操作成功！");
            tabMessageUtil.noticeRefreshByPathname(...REFRESH_PAGE);
            goBack();
            return;
          }

          if (data.enableLevel === 3) {
            message.warn("操作失败，该薪资项关联的薪资单正在审核流程中");
            return;
          }

          confirmFn();
        };

        params.id = editData.id;
        const firstResponse = await onEditSalaryItemFirst(params);
        setLoading(false);

        handleResponse(firstResponse, () => {
          Modal.confirm({
            title: "确定保存？",
            content: `${firstResponse.data.month}月薪资已生成，是否继续`,
            okText: "确定",
            cancelText: "取消",
            onOk: async () => {
              setLoading(true);
              const secondResponse = await onEditSalaryItemSecond(params);
              setLoading(false);

              handleResponse(secondResponse);
            },
          });
        });
      } else {
        // 新增
        const { code, msg = "操作失败，请检查！" } = await onAddSalaryItem(
          params
        );
        setLoading(false);
        if (!isSuccess(code)) {
          message.error(msg);
          return;
        }
        message.success("操作成功");
        tabMessageUtil.noticeRefreshByPathname(...REFRESH_PAGE);
        goBack();
      }
    } catch (e) {
      setLoading(false);
      console.log(e);
    }
  };
  const onSetTaxTypeList = (key) => {
    const queryItemType = key === 2 ? "add" : "reduce";

    setFormItemType(queryItemType);
    getFlowList(queryItemType);
    getParentSalaryItemList(queryItemType);
    form.setFieldsValue({
      salaryType: undefined,
      parentId: undefined,
      formulaFlow: undefined,
      isOffer: key === 2 ? false : undefined,
    });
  };
  const onChangeGantNum = useCallback((value) => {
    const gantData = getFieldValue("salaryItemPeriods") || [];
    gantData.length = Number(value);
    setFieldsValue({
      salaryItemPeriods: gantData,
    });
  }, []);

  const handleEditorFormulaChange = ({
    formula: formulaStr,
    formulaTree,
    validateResult,
  }) => {
    const serverFormula = convert2ServerFormula(formulaTree);
    const hasErrorInServerFormula = validateResult.error.length > 0;

    setFormula(formulaStr);
    form.setFieldsValue({
      serverFormula,
      hasErrorInServerFormula,
    });
  };
  const onValidate = () => {
    validateFields(async (err, values) => {
      try {
        if (!err) {
          let salaryItemSelectStaffList;
          if (
            isPartStaff &&
            selectedStaffEditRef &&
            selectedStaffEditRef.current
          ) {
            salaryItemSelectStaffList = await selectedStaffEditRef.current.getData();
          }
          console.log("Received values of form: ", values);
          const {
            salaryItemPeriods,
            isSpecialGrant,
            hasErrorInServerFormula,
          } = values;
          if (salaryItemSelectStaffList && !salaryItemSelectStaffList.length) {
            message.error("请输入部分人员信息!");
            return;
          }
          if (!specialAmount && !values.serverFormula && !values.formulaFlow) {
            message.error("自定义公式取值及审批流取值至少配置一项");
            return;
          }
          // 特殊发放为true，单独判断发放次数下的取值区间及纳入月份
          if (isSpecialGrant) {
            if (!salaryItemPeriods || !salaryItemPeriods.length) {
              message.error(
                "提交失败，发放次数【取值区间】/【纳入月份】不能为空!"
              );
              return;
            }
            let isEmptyArr = false;
            // salaryItemPeriods length有值，内容没值
            // eslint-disable-next-line no-plusplus
            for (let j = 0; j < salaryItemPeriods.length; j++) {
              const item = salaryItemPeriods[j] || {};
              if (isEmptyArr) {
                break;
              }
              isEmptyArr =
                !item.startMonthDto ||
                !item.salaryMonth ||
                !item.salaryYearType;
            }
            // const isEmptyArr = salaryItemPeriods.every(
            //     item => item.startMonthDto && item.salaryMonth && item.salaryYearType
            // );
            if (isEmptyArr) {
              message.error(
                "提交失败，发放次数【取值区间】/【纳入年份】/【纳入月份】不能为空!"
              );
              return;
            }
            const monthArr = [];
            // eslint-disable-next-line no-restricted-syntax
            for (const item of salaryItemPeriods) {
              const startMonth = item.startMonthDto.month;
              const endMonth = item.endMonthDto.month;
              const { salaryYearType, salaryMonth } = item;

              // 纳入年份选择当年时，纳入月分要>=取值区间右值
              if (salaryYearType === 1 && endMonth > salaryMonth) {
                message.error(
                  "提交失败，【纳入年份】选择当年时，【纳入月份】要>=【取值区间】右值"
                );
                return;
              }

              if (
                monthArr.indexOf(startMonth) !== -1 ||
                monthArr.indexOf(endMonth) !== -1
              ) {
                message.error("提交失败，发放次数【取值区间】月份不可重叠!");
                return;
              }
              // eslint-disable-next-line no-plusplus
              for (let k = startMonth; k <= endMonth; k++) {
                monthArr.push(k);
              }
            }
          }
          if (hasErrorInServerFormula) {
            message.error("公式填写不正确");
            return;
          }
          let data = {};
          // 特殊金额转化
          if (typeof values.specialAmount !== "undefined") {
            data = { ...data, specialAmount: values.specialAmount ? 1 : 0 };
          }
          // 是否是cpf转化
          if (typeof values.cpfEnabled !== "undefined") {
            data = { ...data, cpfEnabled: values.cpfEnabled ? 1 : 0 };
          }
          onAdd({
            ...arrayToString({ ...values, ...data }, arrToStringFields),
            salaryItemSelectStaffList,
          });
        }
      } catch (error) {
        console.log(error, "报错了");
      }
    });
  };

  let cardTitle;
  if (disabled) {
    cardTitle = "薪资项详情";
  } else if (id) {
    cardTitle = "编辑薪资项";
  } else {
    cardTitle = "新增薪资项";
  }

  const ActionFoot = !disabled ? (
    <BottomAction>
      <Button onClick={goBack}>取消</Button>
      <Button type="primary" onClick={onValidate} disabled={disabled}>
        保存
      </Button>
    </BottomAction>
  ) : null;

  useEffect(() => {
    if (organizationCode) {
      queryConditionList(organizationCode).then((response) => {
        if (isSuccess(response)) {
          setConditionList(response.data);
        }
      });
    }
  }, [organizationCode]);

  useEffect(() => {
    getModalDictList();
  }, []);

  useEffect(() => {
    if (id) {
      querySalaryItemInfo(id).then((response) => {
        if (!isSuccess(response)) {
          message.error(response.msg);
        }
        setEditData(response.data);
        if (!itemType) {
          const queryItemType =
            response.data?.itemType === 2 ? "add" : "reduce";
          getParentSalaryItemList(queryItemType);
        }
      });
    }
  }, [id]);
  useEffect(() => {
    setFormItemType(itemType);
    getFlowList(itemType);
    getParentSalaryItemList(itemType);
  }, [itemType]);

  useEffect(() => {
    setSalaryobject(editData.salaryObject);
    setSpecialAmount(editData.specialAmount);
    setFormula(convert2EditorFormula(editData.formulaFunc));
  }, [editData]);

  const taxTypeOptions = getDictList(
    "taxTypeOptions",
    (() => {
      let condition;
      if (getCurrentOrgCountryCode(organizationCode) === SINGAPORE_CODE) {
        condition = "";
      } else {
        condition = formItemType === "add" ? "2" : "3";
      }
      return condition;
    })()
  );

  // 新资类型下拉选项
  const getSalaryTypeOptions = (salaryType) =>
    getDictList("salaryTypeOptions").filter((option) => {
      const filterArray = option?.filter || [];

      return filterArray.some((fil) => String(fil) === String(salaryType));
    });

  return (
    <PageHeaderWrapper type="success">
      <Spin spinning={loading}>
        <PageRouter type="templateSetting">
          <Card
            title={cardTitle}
            bordered={false}
            {...pageTabProps()}
            // extra={
            //     <AuthComponent code="finance:salary:computation:setting:itemlist">
            //         <Button type="link" onClick={() => goToPartTemplate(organizationCode)}>
            //             <span className="iconfont iconoa_maeu_icon_regulation_default" />
            //             <span style={{ marginLeft: '5px' }}>薪资项清单</span>
            //         </Button>
            //     </AuthComponent>
            // }
          >
            <div className={styles.container}>
              <Alert
                message={
                  <Text type="warning">
                    产假：判断员工休产假时系统自动计算险金，无需人工配置，产假结束时补贴走审批流方式发放
                  </Text>
                }
                type="warning"
                style={{ position: "relative", top: -15 }}
              />
              <div className={styles.formContainer}>
                <Form {...formItemLayout}>
                  <Form.Item label="行政机构">
                    <OrganizationNameConnect
                      organizationCode={organizationCode}
                    />
                  </Form.Item>
                  <Form.Item label="设置类型" rules={[{ required: true }]}>
                    <Row gutter={8}>
                      <Col span={14}>
                        {getFieldDecorator("itemType", {
                          initialValue: formItemType === "add" ? 2 : 3,
                          rules: [
                            { required: true, message: "请选择设置类型！" },
                          ],
                        })(
                          <Select
                            placeholder="请选择"
                            disabled={entry === "single"}
                            onChange={onSetTaxTypeList}
                          >
                            {getDictList("salaryItemTypeOptions")
                              .slice(1)
                              .map((item) => (
                                <Option value={item.key} key={item.value}>
                                  {item.value}
                                </Option>
                              ))}
                          </Select>
                        )}
                      </Col>
                      <Col span={10}>
                        {getFieldDecorator("taxType", {
                          initialValue:
                            editData?.taxType ?? taxTypeOptions?.[0]?.key,
                          rules: [
                            { required: true, message: "请选择设置类型！" },
                          ],
                        })(
                          <Select placeholder="请选择" disabled={disabled}>
                            {taxTypeOptions.map((item) => (
                              <Option value={item.key} key={item.value}>
                                {item.value}
                              </Option>
                            ))}
                          </Select>
                        )}
                      </Col>
                      {// 选择其它时
                      getFieldValue("taxType") === 5 ? (
                        <Col span={24} style={{ lineHeight: "18px" }}>
                          <Typography.Text type="secondary">
                            &quot;其他项&quot;只在相关页面做展示，不参与薪资计算
                          </Typography.Text>
                        </Col>
                      ) : null}
                    </Row>
                  </Form.Item>
                  <Form.Item label="上级薪资项">
                    <Row gutter={8}>
                      <Col span={16}>
                        {getFieldDecorator("parentId", {
                          initialValue: editData.parentId || undefined,
                          rules: [
                            {
                              required: true,
                              message: "请选择上级薪资项!",
                              validator: (rule, value) =>
                                // 没有启用【便捷新增】，则为必填项
                                !(!getFieldValue("specialAdd") && !value),
                            },
                          ],
                        })(
                          <Select
                            placeholder="请选择"
                            disabled={disabled || getFieldValue("specialAdd")}
                          >
                            {parentSalaryItemList.map((item) => (
                              <Option value={item.id} key={item.itemName}>
                                {item.itemName}
                              </Option>
                            ))}
                          </Select>
                        )}
                      </Col>
                      <Col span={8}>
                        {getFieldDecorator("specialAdd", {
                          valuePropName: "checked",
                          initialValue: editData.specialAdd || false,
                        })(
                          <Checkbox
                            onChange={(e) => {
                              setTimeout(() => {
                                form.setFieldsValue({ parentId: null });
                                form.validateFields(["parentId"]);
                              }, 0);
                              console.log(e);
                            }}
                            disabled={disabled}
                          >
                            便捷新增
                          </Checkbox>
                        )}
                      </Col>
                    </Row>
                  </Form.Item>

                  {getFieldValue("specialAdd") && (
                    <div className={styles.dynamicItemBox}>
                      <Form.Item
                        label="新增上级薪资项"
                        rules={[{ required: true }]}
                      >
                        {getFieldDecorator("parentName", {
                          initialValue: editData.parentName,
                          rules: [
                            {
                              required: true,
                              message: "请输入新增上级薪资项",
                            },
                            {
                              max: 20,
                              message: "不能超过20个字符",
                            },
                            {
                              pattern: COMMON_NAME.REG,
                              message: COMMON_NAME.MESSAGE,
                            },
                          ],
                        })(
                          <Input
                            placeholder="请输入薪资项名称"
                            maxLength={20}
                          />
                        )}
                      </Form.Item>
                    </div>
                  )}

                  <Form.Item label="新增薪资要素" rules={[{ required: true }]}>
                    <Row gutter={8}>
                      <Col span={16}>
                        {getFieldDecorator("itemName", {
                          initialValue: editData.itemName,
                          rules: [
                            {
                              required: true,
                              message: "请输入新增薪资要素名称",
                            },
                            {
                              max: 100,
                              message: "不能超过20个字符",
                            },
                            {
                              pattern: COMMON_NAME.REG,
                              message: COMMON_NAME.MESSAGE,
                            },
                          ],
                        })(
                          <Input
                            placeholder="请输入新增薪资要素名称"
                            disabled={disabled}
                            maxLength={100}
                          />
                        )}
                      </Col>
                      <Col span={8}>
                        {getFieldDecorator("isSpecialGrant", {
                          valuePropName: "checked",
                          initialValue: editData.isSpecialGrant || false,
                        })(
                          <Checkbox
                            onChange={(e) => {
                              console.log(e);
                            }}
                            disabled={disabled}
                          >
                            特殊发放
                          </Checkbox>
                        )}
                      </Col>
                    </Row>
                  </Form.Item>
                  {getFieldValue("isSpecialGrant") && (
                    <div
                      style={{
                        background: "#FAFAFA",
                        padding: "20px 0",
                        marginBottom: "20px",
                      }}
                    >
                      <Form.Item
                        label="发放次数(次)"
                        style={{ marginBottom: "8px" }}
                      >
                        <Row>
                          <Col span={8}>
                            {getFieldDecorator("grantNum", {
                              initialValue: editData.grantNum || 1,
                            })(
                              <Select
                                placeholder="请选择"
                                disabled={disabled}
                                onChange={onChangeGantNum}
                              >
                                {[1, 2, 3, 4, 5, 6].map((item) => (
                                  <Option value={item} key={item}>
                                    {item}
                                  </Option>
                                ))}
                              </Select>
                            )}
                          </Col>
                        </Row>
                      </Form.Item>
                      {getFieldDecorator("salaryItemPeriods", {
                        initialValue: editData.salaryItemPeriods,
                      })(
                        <Special
                          len={getFieldValue("grantNum")}
                          disabled={disabled}
                        />
                      )}
                    </div>
                  )}
                  <Form.Item
                    label={
                      <span>
                        薪资类型&nbsp;
                        <Tooltip
                          title="薪资类型的选择不影响薪资计算，只影响后续报表分析统计"
                          overlayStyle={{ maxWidth: "unset" }}
                        >
                          <Button className={salaryStyle.iconBtn}>
                            <IconFont type="question-circle" />
                          </Button>
                        </Tooltip>
                      </span>
                    }
                  >
                    {getFieldDecorator("salaryType", {
                      initialValue: editData.salaryType,
                      rules: [
                        {
                          required: true,
                          message: "请选择薪资类型!",
                        },
                      ],
                    })(
                      <Select placeholder="请选择" disabled={disabled}>
                        {getSalaryTypeOptions(getFieldValue("itemType")).map(
                          (item) => (
                            <Option value={item.key} key={item.value}>
                              {item.value}
                            </Option>
                          )
                        )}
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item label="计薪对象">
                    <Row gutter={8}>
                      <Col span={16}>
                        {getFieldDecorator("salaryObject", {
                          initialValue: salaryObject,
                          rules: [
                            {
                              required: true,
                              message: "请选择计薪对象!",
                            },
                          ],
                        })(
                          <Select
                            placeholder="请选择"
                            disabled={disabled}
                            onSelect={handleSalaryObject}
                          >
                            {getDictList("salaryObjectOptions").map((item) => (
                              <Option value={item.key} key={item.value}>
                                {item.value}
                              </Option>
                            ))}
                          </Select>
                        )}
                      </Col>
                      {isPartStaff &&
                        ((
                          <Col span={8}>
                            {getFieldDecorator("specialAmount", {
                              valuePropName: "checked",
                              initialValue: specialAmount,
                            })(
                              <Checkbox
                                onChange={(e) => {
                                  setSpecialAmount(e.target.checked ? 1 : 0);
                                }}
                                disabled={disabled}
                              >
                                特殊金额
                              </Checkbox>
                            )}
                          </Col>
                        ) ||
                          null)}
                    </Row>
                    <Row style={{ marginTop: isPartStaff ? "20px" : "0px" }}>
                      <SelectedStaffEdit
                        wrappedComponentRef={selectedStaffEditRef}
                        showAmount={specialAmount}
                        isFilterField
                        readonly={disabled}
                        list={editData.salaryItemSelectStaffList}
                        visibleStaffSelect={isPartStaff}
                        organizationCode={organizationCode}
                      />
                    </Row>
                  </Form.Item>
                  <Form.Item label="不计薪条件">
                    {getFieldDecorator("salaryNot", {
                      initialValue: makeArray(editData.salaryNot, ","),
                    })(
                      <Select
                        placeholder="请选择"
                        disabled={disabled}
                        allowClear
                        mode="multiple"
                      >
                        {getDictList("salaryNotOptions").map((item) => (
                          <Option value={item.key} key={item.value}>
                            {item.value}
                          </Option>
                        ))}
                      </Select>
                    )}
                  </Form.Item>
                  {getCurrentOrgCountryCode(organizationCode) ===
                    SINGAPORE_CODE && (
                    <Form.Item label="是否CPF" required>
                      {getFieldDecorator("cpfEnabled", {
                        initialValue: !!editData.cpfEnabled || false,
                        valuePropName: "checked",
                      })(<Switch disabled={disabled} />)}
                    </Form.Item>
                  )}
                  {(specialAmount && (
                    <Form.Item label="日期模式" required>
                      {getFieldDecorator("dayMode", {
                        initialValue: editData.dayMode || 1,
                      })(
                        <RadioGroup options={DAY_TYPES} disabled={disabled} />
                      )}
                    </Form.Item>
                  )) ||
                    null}

                  {form.getFieldValue("itemType") === 2 ? (
                    <Form.Item label="是否Offer字段" required>
                      {getFieldDecorator("isOffer", {
                        initialValue: !!editData.isOffer || false,
                        valuePropName: "checked",
                      })(<Switch disabled={disabled} />)}
                    </Form.Item>
                  ) : null}
                  <>
                    {/* 待删除->用新公式编辑器替换旧的编辑器
                                        <Form.Item label="自定义公式取值" extra="请键入自定义公式">
                                            {getFieldDecorator('funcList', {
                                                initialValue: editData.funcList || []
                                            })(<Editor disabled={disabled} conditionList={conditionList} />)}
                                        </Form.Item>
                                        */}
                    {/* <Form.Item label="自定义公式取值">
                                            <FormulaEditor
                                                value={formula || ''}
                                                conditions={selectList}
                                                onFormulaChange={handleEditorFormulaChange}
                                                disabled={disabled || specialAmount}
                                                placeholder={(specialAmount && '特殊金额禁止编辑') || null}
                                            />
                                            {getFieldDecorator('serverFormula')(<Input type="hidden" />)}
                                            {getFieldDecorator('hasErrorInServerFormula')(<Input type="hidden" />)}
                                        </Form.Item> */}
                    <Form.Item label="审批流取值">
                      {getFieldDecorator("formulaFlow", {
                        initialValue: editData.formulaFlow,
                      })(
                        <Select
                          placeholder="请选择"
                          disabled={disabled || specialAmount}
                          allowClear
                        >
                          {flowList
                            .filter(
                              (item) =>
                                !item.used || item.key === editData?.formulaFlow
                            )
                            .map((item) => (
                              <Option value={item.key} key={item.value}>
                                {item.value}
                              </Option>
                            ))}
                        </Select>
                      )}
                    </Form.Item>
                  </>
                  <Form.Item label="备注说明">
                    {getFieldDecorator("remark", {
                      initialValue: editData.remark,
                      rules: [
                        {
                          max: 500,
                          message: "不能超过500个字符",
                        },
                      ],
                    })(
                      <LimitInput
                        placeholder="请输入备注说明"
                        maxLength={500}
                        disabled={disabled}
                        area
                        showNumber
                      />
                    )}
                  </Form.Item>
                </Form>
              </div>
            </div>
          </Card>
        </PageRouter>
        {ActionFoot}
      </Spin>
    </PageHeaderWrapper>
  );
};
export default withRoutePage(
  connect((state, { location }) => ({
    organizationCode: location?.query?.organizationCode,
  }))(Form.create({ name: "templateSalaryModal" })(TemplateSalaryModal))
);
